package com.elsewhat.reddittv.hd.fragments;

import java.lang.reflect.InvocationTargetException;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebSettings.PluginState;
import android.widget.Toast;

import com.elsewhat.reddittv.hd.RedditTVHDActivity;
import com.elsewhat.reddittv.hd.api.RedditPost;

public class YoutubePlayerFragement extends Fragment {
	protected RedditPost redditPost;
	protected WebView webView;
	protected Context context;
	protected YoutubePlayerEventsListener listener;
	
	public YoutubePlayerFragement (YoutubePlayerEventsListener listener,RedditPost redditPost){
		this.redditPost=redditPost;
		this.listener=listener;
	}
	
	public interface YoutubePlayerEventsListener {
		/**
		 * Called when a youtube video has reached the end.
		 * The listener may return a RedditPost that represent the next video to play
		 * 
		 * @param redditPost The reddit post representing the video that just finished playing
		 * @return The next video to play (null to stop playing)
		 */
		RedditPost videoFinished(RedditPost redditPost);
		
	}
	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onActivityCreated(android.os.Bundle)
	 */
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
	}

	/* (non-Javadoc)
	 * @see android.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		context= getActivity();
		webView = new WebView (context);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setPluginState(PluginState.ON);
		webView.setWebChromeClient(new SimpleWebChromeClient());
		
		//String youtubeId = redditPost.getYoutubeId();
		//webView.loadUrl("http://www.youtube.com/embed/"+youtubeId+"?autoplay=1&enablejsapi=1&playerapiid=ytplayer&hd=1");
		//String html = getHTML(redditPost);
		//String html = getHTMLNoIframe(container.getWidth(), container.getHeight());
		String strHtml = getPlayerHTML(container.getWidth()-50, container.getHeight()-50, redditPost);
		//register a javascript interface with the webview for listening to events from the youtube player
		webView.addJavascriptInterface(new RedditTVHDJavascriptInterface(context), "Android");
		//load the youtube player for this reddit post
		webView.loadDataWithBaseURL("http://www.youtube.com", strHtml, "text/html", "utf-8", null);
		Log.d(RedditTVHDActivity.LOG_PREFIX, strHtml);
		Log.d(RedditTVHDActivity.LOG_PREFIX, redditPost.getUrl());
		//webView.loadData(html, "text/html", "utf-8");
		//webView.loadUrl("http://dl.dropbox.com/u/4379928/yt_test.html");

		//origin parameter also`?
		return webView;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onViewCreated(android.view.View, android.os.Bundle)
	 */
	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
	}
	
	protected void playNextVideo(RedditPost newRedditPost){
		String youtubeId=  newRedditPost.getYoutubeId();
		redditPost=newRedditPost;
		Log.i(RedditTVHDActivity.LOG_PREFIX, "Playing next video "+redditPost+ " with youtube id"+youtubeId);
		webView.loadUrl("javascript:playNextVideo('"+youtubeId+"')");
	}
	
	public String getPlayerHTML(int width, int height,RedditPost redditPost){
		String strHTML = 
		"<hmtl>\n"+
		"<head><script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js\"></script>\n"+
		"<script type=\"text/javascript\">\n"+
		"var ytplayer;\n"+
		"function playNextVideo(youtubeId) {\n"+
		"  if(ytplayer!=null){\n" +
		"     ytplayer.loadVideoById(youtubeId);\n"+
		"  }\n"+
		"}\n"+
		"function onPlayerError(errorCode) {\n"+
		"  //Android.onPlayerError(errorCode);\n"+
		"}\n"+

		"function onPlayerStateChange(newState) {\n"+
		"  //alert(newState);\n"+
		"  Android.onPlayerStateChange(newState);\n"+
		"}\n"+
		"// This function is automatically called by the player once it loads\n"+
		"function onYouTubePlayerReady(playerId) {\n"+
		"  ytplayer = document.getElementById(\"ytPlayer\");\n"+
		"  ytplayer.addEventListener(\"onStateChange\", \"onPlayerStateChange\");\n"+
		"  ytplayer.addEventListener(\"onError\", \"onPlayerError\");\n"+
		"}\n"+
		"var videoID = \""+redditPost.getYoutubeId()+"\";\n"+
		"var params = { allowScriptAccess: \"always\" };\n"+
		"var atts = { id: \"ytPlayer\" };\n"+
		"swfobject.embedSWF(\"http://www.youtube.com/v/\" + videoID +\n"+
		"	     \"?version=3&enablejsapi=1&playerapiid=player1&hd=1&autoplay=1&fs=1\",\n"+
		"	     \"videoDiv\", \""+width+"\", \""+height+"\", \"9\", null, null, params, atts);\n"+
		"</script>\n"+
		"</head>\n"+
		"<div id=\"videoDiv\"/>";
		return strHTML;
	}
	
	/*
	public String getHTML(RedditPost redditPost){
		String html= "<script src=\"http://www.youtube.com/player_api\"></script>\n"+
			"<script type=\"text/javascript\">\n"+
			"var player;\n"+
	"\n"+
			"function onPlayerReady(event) {\n"+
			"	Android.onPlayerReady('onPlayerReady');\n"+
			"	//event.target.playVideo();\n"+
			"}\n"+
	"\n"+
			"function onPlayerStateChange(event) {\n"+
			"	Android.onPlayerReady(''+event);\n"+
			"}\n"+
			"//setup player and event listeners\n"+
			"function onYouTubePlayerAPIReady() {\n"+
			"	//alert('In onYouTubePlayerAPIReady');\n"+
			"	//player = new YT.Player('ytplayer', {\n"+
			"	//	events: {\n"+
			"	//		'onReady': onPlayerReady,\n"+
			"	//		'onStateChange': onPlayerStateChange\n"+
			"	//	}\n"+
			"	//});\n"+
			"}\n"+
	"\n"+
			"</script>\n"+
	"\n"+
			"<iframe class=\"youtube-player\" style=\"border: 0; width: 100%; height: 100%\" id=\"ytplayer\" type=\"text/html\" src=\"http://www.youtube.com/embed/"+
			redditPost.getYoutubeId()+"?enablejsapi=1\" frameborder=\"0\">\n"+
			"</iframe>\n";
		return html;
	}
	
	public String getHTMLNoIframe(int width,int height){
		String html= "<script src=\"http://www.youtube.com/player_api\"></script>\n"+
		"<script type=\"text/javascript\">\n"+
		"var player;\n"+
"\n"+
		"function onPlayerReady(event) {\n"+
		"	Android.onPlayerReady('onPlayerReady');\n"+
		"	//event.target.playVideo();\n"+
		"}\n"+
"\n"+
		"function onPlayerStateChange(event) {\n"+
		"	Android.onPlayerReady(''+event);\n"+
		"}\n"+
		"//setup player and event listeners\n"+
		"function onYouTubePlayerAPIReady() {\n"+
			"	player =document.getElementById('ytplayer2');\n" +
			" Android.onPlayerReady('testing' + player);\n"+
			"   player.addEventListener(\"onStateChange\", \"onPlayerStateChange\");\n"+
		"}\n"+
"\n"+
		"</script>\n"+
		"<object id=\"ytplayer\" width=\""+width+"\" height=\""+height+"\">  <param name=\"movie\" value=\"http://www.youtube.com/v/u1zgFlCw8Aw?enablejsapi=1\"></param><param name=\"allowScriptAccess\" value=\"always\"></param>\n"+
		"<embed id=\"ytplayer2\" src=\"http://www.youtube.com/v/u1zgFlCw8Aw?enablejsapi=1\" type=\"application/x-shockwave-flash\" allowscriptaccess=\"always\" width=\""+width+"\" height=\""+height+"\"></embed>\n"+
		"</object>";
		return html;
	}
	*/
	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onDestroy()
	 */
	@Override
	public void onDestroy() {
		Log.w(RedditTVHDActivity.LOG_PREFIX, "In onDestroy");
		if(webView!=null){
		//	webView.destroy();
		}
		super.onDestroy();
	}
	/* (non-Javadoc)
	 * @see android.app.Fragment#onPause()
	 */
	@Override
	public void onPause() {
		Log.w(RedditTVHDActivity.LOG_PREFIX, "In onPause");
		
		webView.pauseTimers();
		try {
			Class.forName("android.webkit.WebView").getMethod("onPause", (Class[]) null).invoke(webView, (Object[]) null);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onPause();
	}
	/* (non-Javadoc)
	 * @see android.app.Fragment#onStop()
	 */
	@Override
	public void onStop() {
		Log.w(RedditTVHDActivity.LOG_PREFIX, "In onStop");
		if(webView!=null){
		//	webView.destroy();
		}
		
		super.onStop();
	}

	
	/* (non-Javadoc)
	 * @see android.app.Fragment#onResume()
	 */
	@Override
	public void onResume() {
		Log.w(RedditTVHDActivity.LOG_PREFIX, "In onResume");
		webView.resumeTimers();
		try {
			Class.forName("android.webkit.WebView").getMethod("onResume", (Class[]) null).invoke(webView, (Object[]) null);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.onResume();
	}


	public class RedditTVHDJavascriptInterface {
	    Context mContext;
	    public static final int EVENT_FINISHED_PLAYING=0;

	    /** Instantiate the interface and set the context */
	    RedditTVHDJavascriptInterface(Context c) {
	        mContext = c;
	    }

	    /** Show a toast from the web page */
	    public void onPlayerReady(String msg) {
	        Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
	    }
	    /** Show a toast from the web page */
	    public void onPlayerStateChange(int newState) {
	    	if(newState==EVENT_FINISHED_PLAYING){
	    		RedditPost newRedditPost = listener.videoFinished(redditPost);
	    		if(newRedditPost!=null){
	    			playNextVideo(newRedditPost);
	    		}
	    	}
	        //Toast.makeText(mContext, "State of youtubeplayer " + newState, Toast.LENGTH_SHORT).show();
	    }
	    
	    public void onPlayerError(String error) {
	        Toast.makeText(mContext, error, Toast.LENGTH_SHORT).show();
	    }
	}
	
	private class SimpleWebChromeClient extends WebChromeClient {

		/* (non-Javadoc)
		 * @see android.webkit.WebChromeClient#onShowCustomView(android.view.View, android.webkit.WebChromeClient.CustomViewCallback)
		 */
		@Override
		public void onShowCustomView(View view, CustomViewCallback callback) {
			super.onShowCustomView(view, callback);
			Log.w(RedditTVHDActivity.LOG_PREFIX, "In OnShowCustomView");
		}
		
	}

}
